﻿using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;

// For Adding an image
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;

using Angerona.Model;
using Microsoft.Phone.Scheduler;
using System.Windows.Media;
using System.IO;
using Microsoft.Phone;
using System.IO.IsolatedStorage;

namespace Angerona.Views
{
    public partial class AddCar : PhoneApplicationPage
    {
        PhotoChooserTask photoChooserTask = new PhotoChooserTask();
        bool hasSaveFired = false;
        DateTime defaultDate = new DateTime(2013, 1, 1);
        string nameOfImage;

        public AddCar()
        {
            InitializeComponent();
            ApplicationBarInitializer();
            this.photoChooserTask.Completed += photoChooserTask_Completed;
            this.DataContext = App.ViewModel;
            var v = (Visibility)Application.Current.Resources["PhoneLightThemeVisibility"];
            if (v == Visibility.Visible)
            {
                Uri invertedOminImage = new Uri("/Img/AppIcons/user_100_100_INV.png", UriKind.Relative);
                ImageSource invertedOminImageSource = new BitmapImage(invertedOminImage);
                Uri invertedColorImage = new Uri("/Img/AppIcons/pictureAdd_100_100_INV.png", UriKind.Relative);
                ImageSource sourceOfImageInverted = new BitmapImage(invertedColorImage);
                imageOfSelectedCar.Source = sourceOfImageInverted;
            }
            this.carfuel.ItemsSource = new List<String>() { AngeronaLang.fuelgasoline, AngeronaLang.fueldiesel, AngeronaLang.fuelgpl, AngeronaLang.fuelelectric };
            carproductiondate.Value = defaultDate;
            carboughtdate.Value = defaultDate;
            assurancedate.Value = defaultDate;
            bollodate.Value = defaultDate;
            revisiondate.Value = defaultDate;
            this.carboughtdate.ValueChanged += new EventHandler<DateTimeValueChangedEventArgs>(picker_ValueChanged);
            this.carproductiondate.ValueChanged += new EventHandler<DateTimeValueChangedEventArgs>(picker_ValueChanged);
            this.assurancedate.ValueChanged += new EventHandler<DateTimeValueChangedEventArgs>(picker_ValueChanged);
            this.bollodate.ValueChanged += new EventHandler<DateTimeValueChangedEventArgs>(picker_ValueChanged);
            this.revisiondate.ValueChanged += new EventHandler<DateTimeValueChangedEventArgs>(picker_ValueChanged);
        }

        private void ApplicationBarInitializer()
        {
            ApplicationBar = new ApplicationBar();
            ApplicationBar.Mode = ApplicationBarMode.Default;
            ApplicationBar.Opacity = 1.0;
            ApplicationBar.IsVisible = true;
            ApplicationBar.IsMenuEnabled = false;

            // save button
            ApplicationBarIconButton btn_save = new ApplicationBarIconButton();
            btn_save.IconUri = new Uri("/Img/appbar_save.png", UriKind.Relative);
            btn_save.Text = AngeronaLang.save;
            ApplicationBar.Buttons.Add(btn_save);
            btn_save.Click += new EventHandler(btn_save_Click);

            //help button
            ApplicationBarIconButton btn_help = new ApplicationBarIconButton();
            btn_help.IconUri = new Uri("/Img/appbar_help.png", UriKind.Relative);
            btn_help.Text = AngeronaLang.help;
            ApplicationBar.Buttons.Add(btn_help);
            btn_help.Click += new EventHandler(btn_help_Click);

            // undo button
            ApplicationBarIconButton btn_undo = new ApplicationBarIconButton();
            btn_undo.IconUri = new Uri("/Img/appbar_cancel.png", UriKind.Relative);
            btn_undo.Text = AngeronaLang.undo;
            ApplicationBar.Buttons.Add(btn_undo);
            btn_undo.Click += new EventHandler(btn_undo_Click);
        }

        private void btn_undo_Click(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }

        private void btn_help_Click(object sender, EventArgs e)
        {
            MessageBox.Show(AngeronaLang.help_add_car, AngeronaLang.help, MessageBoxButton.OK);
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            hasSaveFired = true;
            string saveThisFuckinNameOrcoddio = nameOfImage;
            // Check for 0 input data
            if (carname.Text.Length == 0)
            {
                MessageBox.Show(AngeronaLang.addcarerror);
            }
            else
            {
                //checking for name already in using
                int i = 0;
                bool samename = false;
                int idmax = App.ViewModel.getNumbersOfVehicles();
                List<int> idlist = App.ViewModel.getVehicleIdlist();
                while (i < idmax)
                {
                    VehiclesTable temp = App.ViewModel.getElementWithID(idlist[i]);
                    if (carname.Text == temp.VehicleName | carplate.Text == temp.PlateNumber)
                    {
                        samename = true;
                        MessageBox.Show(AngeronaLang.nameAlreadyUsed);
                        break;
                    }
                    i++;
                }
                //Only if name is non-used
                if (!samename)
                {
                    VehiclesTable newVehicles = new VehiclesTable
                    {

                        ImageOfCar = nameOfImage,
                        VehicleName = carname.Text,
                        Manufacter = carmanufacter.Text,
                        VehicleModel = carmodel.Text,
                        FuelType = carfuel.SelectedItem.ToString(),
                        KwPower = carkw.Text,
                        HorsePower = carhorse.Text,
                        EngineCapacity = carvolume.Text,
                        PlateNumber = carplate.Text,
                        SerialNumber = carserial.Text,
                        ProductionDate = (DateTime)carproductiondate.Value,
                        PurchasedDate = (DateTime)carboughtdate.Value,
                        PurchasedKm = carinitialkm.Text,
                        TraveledKm = cartraveledkm.Text,
                        AssuranceCompany = assurancecompany.Text,
                        AssuranceNumber = assurancenumber.Text,
                        AssuranceDate = (DateTime)assurancedate.Value,
                        Bollo = (DateTime)bollodate.Value,
                        Revision = (DateTime)revisiondate.Value,

                    };

                    App.ViewModel.AddItem(newVehicles);
                    SetReminders(newVehicles);
                    NavigationService.GoBack();
                }
            }
        }

        /// <summary>
        /// Check if the datepicker is changed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void picker_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
        {
            DatePicker dp = (DatePicker)sender;
            dp.Value = CheckAgeOrDefault((DateTime)dp.Value);
            if (dp.Name == "assurancedate" | dp.Name == "bollodate" | dp.Name == "revisiondate")
                if (dp.Value < DateTime.Now & dp.Value != defaultDate)
                {
                    dp.Value = defaultDate;
                    MessageBox.Show(AngeronaLang.ReminderErrorDate, AngeronaLang.Error, MessageBoxButton.OK);
                }
            sender = dp;
        }

        /// <summary>
        /// Checks if the data into the datepicker is NOT inferior to 1754,1,1. 
        /// Eventually it shows a messageBox with the alert.
        /// </summary>
        /// <param name="x">Input Datetime parameter to be checked</param>
        /// <returns></returns>
        private DateTime CheckAgeOrDefault(DateTime x)
        {
            DateTime temp = new DateTime(1754, 1, 1);
            if (x < temp)
            {
                MessageBox.Show(AngeronaLang.ReminderToOldDate, AngeronaLang.Error, MessageBoxButton.OK);
                x = defaultDate;
            }
            return x;
        }

        /// <summary>
        /// Set the reminder for the vehicle passed.
        /// </summary>
        /// <param name="VehicleToBeSetted">Input VehiclesTable element to be setted</param>
        private void SetReminders(VehiclesTable VehicleToBeSetted)
        {
            //Reminder for Assurance expiration
            if (VehicleToBeSetted.AssuranceDate != defaultDate)
            {
                DateTime AssuranceDate = (DateTime)VehicleToBeSetted.AssuranceDate;

                ScheduledAction OldReminder = ScheduledActionService.Find("AssuranceDate" + VehicleToBeSetted.VehicleName);
                if (OldReminder != null)
                    ScheduledActionService.Remove(OldReminder.Name);

                //Create the reminder
                Reminder AssuranceDateReminder = new Reminder("AssuranceDate" + VehicleToBeSetted.VehicleName)
                {
                    BeginTime = AssuranceDate.AddHours(9),
                    Title = AngeronaLang.assuranceReminderTitle,
                    Content = VehicleToBeSetted.VehicleName + ": " + AngeronaLang.assuranceReminderContenent,
                    //when a user interact with the reminder the App will open on User view
                    NavigationUri = new Uri("/Views/Vehicles.xaml", UriKind.Relative),

                };
                ScheduledActionService.Add(AssuranceDateReminder);
            }

            //Reminder for Bollo expiration
            if (VehicleToBeSetted.Bollo != defaultDate)
            {
                DateTime Bollo = (DateTime)VehicleToBeSetted.Bollo;

                ScheduledAction OldReminder = ScheduledActionService.Find("Bollo" + VehicleToBeSetted.VehicleName);
                if (OldReminder != null)
                    ScheduledActionService.Remove(OldReminder.Name);

                //Create the reminder
                Reminder BolloReminder = new Reminder("Bollo" + VehicleToBeSetted.VehicleName)
                {
                    BeginTime = Bollo.AddHours(9),
                    Title = AngeronaLang.bolloReminderTitle,
                    Content = VehicleToBeSetted.VehicleName + ": " + AngeronaLang.bolloReminderContenent,
                    //when a user interact with the reminder the App will open on User view
                    NavigationUri = new Uri("/Views/Vehicles.xaml", UriKind.Relative),

                };
                ScheduledActionService.Add(BolloReminder);
            }

            //Reminder for Revision expiration
            if (VehicleToBeSetted.Revision != defaultDate)
            {
                DateTime Revision = (DateTime)VehicleToBeSetted.Revision;

                ScheduledAction OldReminder = ScheduledActionService.Find("Revision" + VehicleToBeSetted.VehicleName);
                if (OldReminder != null)
                    ScheduledActionService.Remove(OldReminder.Name);

                //Create the reminder
                Reminder RevisionReminder = new Reminder("Revision" + VehicleToBeSetted.VehicleName)
                {
                    BeginTime = Revision.AddHours(9),
                    Title = AngeronaLang.revisionReminderTitle,
                    Content = VehicleToBeSetted.VehicleName + ": " + AngeronaLang.revisionReminderContenent,
                    //when a user interact with the reminder the App will open on User view
                    NavigationUri = new Uri("/Views/Vehicles.xaml", UriKind.Relative),

                };
                ScheduledActionService.Add(RevisionReminder);
            }
        }

        private void carname_LostFocus(object sender, RoutedEventArgs e)
        {
            if (!hasSaveFired)
            {
                int i = 0;
                int idmax = App.ViewModel.getNumbersOfVehicles();
                List<int> idlist = App.ViewModel.getVehicleIdlist();
                while (i < idmax)
                {
                    VehiclesTable temp = App.ViewModel.getElementWithID(idlist[i]);
                    if (carname.Text == temp.VehicleName)
                    {
                        MessageBox.Show(AngeronaLang.nameAlreadyUsed);
                        break;
                    }
                    i++;
                }
            }
        }

        private void select_Photo_Click(object sender, RoutedEventArgs e)
        {
            photoChooserTask.PixelHeight = 200;
            photoChooserTask.PixelWidth = 400;
            photoChooserTask.Show();
        }

        void photoChooserTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                BitmapImage image = new BitmapImage();
                MemoryStream ms = new MemoryStream();
                image.SetSource(e.ChosenPhoto);
                DateTime time = DateTime.Now;
                nameOfImage = time.Millisecond.ToString() + time.Hour.ToString() + time.Minute.ToString() + time.Second.ToString();

                WriteableBitmap writeableImage = new WriteableBitmap(image);
                
                // Select the image for xaml
                imageOfSelectedCar.Source = writeableImage;
                
                // Writes the image as jpeg inside the stream MemoryStream ms
                writeableImage.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);

                // Saving image into isolatedStorage
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // Nome dell'immagine = tempo 
                    IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(nameOfImage);
                    Extensions.SaveJpeg(writeableImage, fileStream, writeableImage.PixelWidth, writeableImage.PixelHeight, 0, 100);
                    fileStream.Close();
                }
            }
        }
    }
}